import {openBluetoothAdapter,createBLEPeripheralServer} from "../../../utils/ble";




const uuid3 = '00001000-0000-1000-8000-00805f9b34fb'
const serviceId = '00001001-0000-1000-8000-00805f9b34fb'
const characteristicId = '00001999-0000-1000-8000-00805f9b34fb'
// 上面需要配置主机的 serviceId 和 characteristicId


// ArrayBuffer转16进制字符串示例
function ab2hex(buffer) {
  let hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
function ab2str(u, f) {
		var b = new Blob([u]);
		var r = new FileReader();
		r.readAsText(b, 'utf-8');
		r.onload = function (e) {
			f && f(e.target.result);
				//console.log(e.target.result, '===')
		}
}


function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// slave/slave.js
Page({
  data: {
    textList: [],
		connects:[]
  },

  onLoad: function (options) {
    wx.onBLEPeripheralConnectionStateChanged(res => {
      console.log('connect',res)
      const connects = this.data.connects
      const idx = inArray(connects, 'deviceId', res.deviceId)
      if (idx >= 0) {
        connects[idx] = res
      } else {
        connects.push(res)
      }
      this.setData({ connects })
    })
  },

	async createServer(){
		var _openBluetoothAdapter = await openBluetoothAdapter('peripheral');
		if(_openBluetoothAdapter.errno == '0'){
			var _createBLEPeripheralServer = await createBLEPeripheralServer();
			if(_createBLEPeripheralServer.errno == '0'){
				//可创建多个服务
				this.server = _createBLEPeripheralServer.server;
				this.data.textList.push('创建服务成功，Id为：'+this.server.serverId);
				this.setData({textList:this.data.textList});
				// 监听收到数据
				
				this.server.onCharacteristicReadRequest(res => {
        const { serviceId, characteristicId, callbackId } = res
        const buffer = new ArrayBuffer(1)
        const dataView = new DataView(buffer)
        const newValue = Math.ceil(Math.random() * 10)
        dataView.setUint8(0, newValue)
        console.log('onCharacteristicReadRequest', res, newValue)
        this.server.writeCharacteristicValue({
          serviceId,
          characteristicId,
          value: buffer,
          needNotify: true,
          callbackId
        })
      })
      	// 监听收到数据
      	this.server.onCharacteristicWriteRequest(res => {
        console.log('onCharacteristicWriteRequest', res)
        const { serviceId, characteristicId, value, callbackId } = res
				ab2str(value,function(str){
					wx.showToast({
						title: '收到主机数据'+str
					})					
				})
				
  
        this.server.writeCharacteristicValue({
          serviceId,
          characteristicId,
          value,
          needNotify: true,
          callbackId
        })
      })
				this.addService();
			}
		}else{
			wx.showToast({title: '请打开蓝牙', icon:'none'})			
		}
	},
	addService() {
    const buffer = new ArrayBuffer(1)
    const dataView = new DataView(buffer)
    dataView.setUint8(0, 2)
    const descriptorBuffer = new ArrayBuffer(1)
    const dataView2 = new DataView(descriptorBuffer)
    dataView2.setInt8(0, 3)
    const service = {
      uuid: serviceId,
      characteristics: [{
        uuid: characteristicId,
        properties: {
          write: true,
          read: true,
          notify: true,
          indicate: true
        },
        permission: {
          readable: true,
          writeable: true,
          readEncryptionRequired: true,
          writeEncryptionRequired: true
        },
        value: buffer,
        descriptors: [{
          uuid: uuid3,
          permission: {
            write: true,
            read: true
          },
          value: descriptorBuffer
        }]
      }]
    }

    this.server.addService({
      service
    }).then(res => {
			this.data.textList.push('添加服务成功');
			this.setData({textList:this.data.textList});
			this.startAdvertising();
    },(rej) => {
      if (rej.errCode === 10001) {
        wx.showToast({
          title: '请打开蓝牙',
        })
      } else {
        wx.showModal({
          title: '创建失败',
          content: `错误码: ${rej.errCode}`
        })
      }
    })
  },
  startAdvertising() {
    const buffer = new ArrayBuffer(1)
    const dataView = new DataView(buffer)
    dataView.setInt8(0, 4)
    this.server.startAdvertising({
      advertiseRequest: {
        connectable: true,
        deviceName: 'bleysten',
        serviceUuids: [serviceId],
      },
      powerLevel: 'medium'
    }).then(res => {
      console.log('startAdvertising', res)
			this.data.textList.push('添加广播成功');
			this.setData({textList:this.data.textList});			
    })
  },







  closeServer() {
    this.server.close()
    wx.showToast({
      title: '关闭 server',
    })
  },
  chaneMode() {
    wx.navigateBack();
  },
  onConfirm(e) {
    console.log('onConfirm')
    const n = e.detail.value * 1
    const buffer = new ArrayBuffer(1)
    const dataView = new DataView(buffer)
    dataView.setUint8(0, n)
		console.log('dataView',dataView);
    this.server.writeCharacteristicValue({
      serviceId: serviceId,
      characteristicId: characteristicId,
      value: buffer,
      needNotify: true
    })
    wx.showModal({
      title: '写入成功',
      content: '请在主机查看'
    })
		
  },
  showInput() {
    this.setData({
      input: !this.data.input
    })
  },
  
	
	
  removeService() {
    this.server.removeService({
      serviceId: serviceId
    }).then(res => {
      wx.showToast({
        title: '关闭服务',
      })
      console.log('removeService', res)
    })
  },


  stopAdvertising() {
    this.server.stopAdvertising()
    wx.showToast({
      title: '关闭广播',
    })
  },

  closeBluetoothAdapter() {
		this.stopAdvertising();
		this.removeService();
		this.server.close();
    wx.showToast({
      title: '结束流程',
    })
    wx.closeBluetoothAdapter()
  },
	gotMe(){
		wx.getConnectedBluetoothDevices({
      success: (res) => {
        console.log('getConnectedBluetoothDevices success', res)

      },			
		})	
	},
	goToCenter(){
		wx.redirectTo({
			url: '/pages/ble/center/center'
		})		
	},
	
  onUnload: function () {
    //this.data.servers.forEach(server => {
     // this.server.close()
    //})
  },
})